<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 
 * 主函数，用来做程序，所有控制器都要经过这里
 * 
 * @author yunyun
 * 
 */
 
class MY_Controller extends CI_Controller {
	
	var $CI 				= null;
	
	/**
	 * 
	 * @var $model_path 模型路径
	 * @var $view_path 视图路径
	 * @var $lang_path 语言路径
	 * @var $validation_path 脚本检验
	 * 
	 */
	
	var $model_path 		= '';
	var $view_path 			= '';
	var $lang_path 			= '';
	var $validation_path	= '';


	var $keyword = "";
	var $description = "";

	
	
	public function __construct()
	{
		parent::__construct();
		
		//初始化ci实例
		$this->CI = & get_instance();

		$this->_check_options();
		//@header("ACCESS-CONTROL-ALLOW-ORIGIN: *");
		/**
		 * model
		 */
		if(trim($this->model_path) != null)
		{
			$this->CI->load->model($this->model_path);		
		}

		/**
		 * 加载语言
		 */
		if(trim($this->lang_path) != '')
		{
			$this->CI->lang->load($this->lang_path);
		}

		//检测token
        $this->CI->token_lib->check();
		
		log_message('debug', "MY_Controller Class Initialized.");
	}

	private function _check_options()
	{
		
		
		//如果是 options
		$method_type = $this->CI->input->method();
		if($method_type == "options" )
		{
			//@header("Access-Control-Max-Age: 3600");
			//@header("X-Frame-Options: deny");
			//@header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
			exit(0);
		}
	}

    /**
     * 算分页函数
     *
     * @param int $total_nums 总条数
     * @param int $currentPage 第几页 默认第一页
     * @param int $pageSize 几条分页 默认10条分页
     * @param string $TotalNumStr 总条数字符串
     * @param string $CurrentPageStr 当前要第几页字符串
     * @param string $TotalPageCountStr 总页数
     * @param string $PageSizeStr 几条数据分页
     * @return mixed
     */
	public function get_page($total_nums = 0,$currentPage = 0,$pageSize = 0)
	{
        if($currentPage <= 0)  $currentPage = $this->CI->input->post("currentPage");
        if($pageSize <= 0) $pageSize = $this->CI->input->post("pageSize");

        $TotalNumStr="totalSize";
        $CurrentPageStr="pageNum";
        $TotalPageCountStr="totalPages";
        $PageSizeStr = "PageSize";

		if($total_nums <= 0)  $total_nums = 0;
        if($currentPage <= 0) $currentPage = 1;
        if($pageSize <= 0) $pageSize = 10;

		$res_arr["data"][$TotalNumStr] = $total_nums;
		$res_arr["data"][$CurrentPageStr] = $currentPage;
		$res_arr["data"][$PageSizeStr] = $pageSize;
		$res_arr["data"][$TotalPageCountStr] = @ceil($total_nums/$pageSize);
		$res_arr["limit"] = $pageSize.",".$pageSize*($currentPage-1);

		return $res_arr;
	}

    /**
     * @param string $key
     * @param string object array
     * @return mixed|null
     */
	public function get_input($key = "",$type = "object")
	{
		$instr = @$this->CI->input->raw_input_stream;

		if($type == "array")
        {
            $obj_arr = json_decode($instr,true);
        }
        else
        {
            $obj_arr = json_decode($instr);
        }

		if($key == NULL)
		{
			return $obj_arr;
		}
		else
		{
			if(isset($obj_arr->$key))
			{
				return $obj_arr->$key;
			}
			return NULL;
		}

	}
	
	public function view($path = "", $data = NULL, $type = false)
	{
		$this->CI->load->view($path,$data,$type);
	}

	public function api($type = 500, $data = NULL, $message = "")
	{
		//$this->_add_log();
		show_message($type,$data,$message); exit();
	}

	/**
	 * 添加日志
	 */

	public function write_logs($type = 304,$data_arr = NULL,$message = "")
	{
		$this->CI->load->model("log/log_model");

		$inset_data["method"] = $this->CI->input->method(); //操作方式
		$inset_data["params"] = $this->CI->input->raw_input_stream; //请求参数
		$inset_data["ip"] =  $this->CI->input->ip_address(); //请求参数
		$inset_data["ret_data"] =  json_encode($data_arr,JSON_UNESCAPED_UNICODE); //返回数据
		$inset_data["static"] =  $type; //状态
		$inset_data["message"] =  $message; //
		$inset_data["uri"] =  uri_string(); //
		$inset_data["admin_id"] =  $this->CI->token_lib->get_data("admin_id"); //

		$this->CI->log_model->adds($inset_data);
	}

	protected function pic2bq($string = NULL)
    {
        #
        $pic_url = get_web_url("pic","","");
        $bq_name = "{{PICURL}}";
        $string = str_replace($pic_url,$bq_name,$string);
        return $string;
    }

    protected function bq2pic($string = NULL)
    {
        $pic_url = get_web_url("pic","","");
        $bq_name = "{{PICURL}}";
        $string = str_replace($bq_name,$pic_url,$string);
        return $string;
    }


    protected function time($time = 0,$type_str = "Y-m-d H:i:s")
    {
    	return date($type_str,$time);
    }

    protected function date($time = 0,$type_str = "Y-m-d")
    {
    	return date($type_str,$time);
    }

    protected function pic2url($string = NULL)
    {
    	if($string)
    	{
            $pic_url = base_url($string);
    		return $pic_url;
    	}
    	return "";
    }


    public function html($title="",$js="")
	{
		$dir_arr = array(
			"meta" => "meta",
			"header" => "header",
			"menu" => "menu",
			"footer" =>"footer"
		);

		$data_arr = array();
		//$data_arr["menu_arr"] = $this->CI->menu_lib->get_menu_arr();


		$html_arr = array();
		//$html_arr["_page_arr"] = $this->_page_arr;
		//$html_arr["_base_page"] = $this->_base_page;

		return $this->_html($title,$js,$dir_arr,$data_arr,$html_arr);
	}
	
	/**
	 * 私人 html
	 * 
	 * @param unknown_type $title
	 * @param unknown_type $js
	 * @param unknown_type $menu
	 * @param unknown_type $left
	 * 
	 */
	private function _html($title='',$js="",$dir_arr = array(),$data_arr = array(),$html = array())
	{
		$this->CI->load->helper('url');


		$data_arr['title'] = site_web_name($title);
		$data_arr['keyword'] = site_web_keyword($this->keyword);
		$data_arr['description'] = site_web_description($this->description);
		$data_arr['js'] = $this->str2array($js);
		
		
		if($dir_arr)
		{
			foreach($dir_arr as $key => $val){
				$html[$key] = $this->CI->load->view($val, $data_arr, true);
			}
		}
		
		return $html;
	}
	
	/**
	 * 
	 * 用户信息跳转
	 * 
	 * @param bool $success true 成功 false 失败
	 * @param string $source_url
	 * @param string $message
	 * 
	 */
	public function remind($success,$source_url ='/',$message='')
	{
		
		$this->CI->session->set_flashdata("return_message_info",$message);
		$this->CI->session->set_flashdata("return_url_info",$source_url);
		if($success == true)
		{
			redirect('/remind/index/'.'success');
		}
		else
		{
			redirect('/remind/index/'.'fail');
		}
		
	}


	/**
     * 将字符串转换为数组，并反向键值关系
	 *
     * @param string $str
     */
    private function str2array($str)
    {
        $ret = explode(',', $str);
        return array_flip($ret);
    }
	
}